package com.yingside.collection;

import java.util.Iterator;

public class Queue<T> implements Iterable<T> {

    private class Node {//定义节点类
        T item;
        Node nextNode;

        public Node(T item) {
            this.item = item;
        }
    }

    private Node firstNode;
    private Node lastNode;
    private int N;

    public boolean isEmpty() {
        return firstNode == null;
    }

    public int size() {
        return N;
    }

    public void enQueue(T item) {// 队尾插入新节点
        Node oldNode = lastNode;
        lastNode = new Node(item);
        if (isEmpty()) {
            firstNode = lastNode;
        } else {
            oldNode.nextNode = lastNode;
        }
        N++;
    }

    public T deQueue() {// 队首插入新节点
        T item = firstNode.item;
        firstNode = firstNode.nextNode;
        if (isEmpty())
            lastNode = null;
        N--;
        return item;
    }

    // 以下实现Iterator 接口 ，方便迭代输出 ， 可选实现
    public Iterator iterator() {
        return new queueIterator();
    }

    private class queueIterator<T> implements Iterator<T> {
        Node iteratorNode = firstNode;

        @Override
        public boolean hasNext() {
            return iteratorNode != null;
        }

        @Override
        public T next() {
            T item = (T) iteratorNode.item;
            iteratorNode = iteratorNode.nextNode;
            return item;
        }

    }

    public static void main(String[] args) {
        Queue<String> queue = new Queue<>();
        queue.enQueue("aa");
        queue.enQueue("bb");
        queue.enQueue("cc");
        queue.enQueue("dd");

        Iterator<String> iterator = queue.iterator();

        while(iterator.hasNext()){
            String next = iterator.next();
            System.out.println("next = " + next);
        }

        queue.deQueue();

        iterator = queue.iterator();


        while(iterator.hasNext()){
            String next = iterator.next();
            System.out.println("next2 = " + next);
        }
    }

}